<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Input;
use Spatie\Permission\Models\Permission;

class PermissionController extends Controller
{
    public function __construct(){
        $this->middleware('auth');
    }

    public function index()
    {
        $permission = Permission::orderBy('id')->paginate(15);
        return view('permission',[
            'permission'=>$permission
        ]);
    }

    public function create(){
        $id = Input::get('id');
        $permission = Permission::findById($id);
        return response()->json([
            'permission' => $permission
        ]);
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $input = Input::all();
        if(Input::ajax()) {
            $messages = [
                'required' => ':attribute值不能为空！',
                'unique' => ':attribute已存在'
            ];
            $this->validate($request, [
                'name' => 'bail|required|unique:permissions|max:255',
            ], $messages);
            $permission = Permission::create(['name'=>$input['name'],'description'=>$input['description']]);
            return response()->json([
                'permission' => $permission
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {

    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $input = $request->all();
        if(Input::ajax()){
            $messages = [
                'required' => ':attribute值不能为空！',
                'unique' => ':attribute已存在'
            ];
            $this->validate($request, [
                'name' => 'bail|required|unique:permissions,name,'.$id.'|max:255',
            ], $messages);
            $permission = Permission::findById($id);
            $permission->name = $input['name'];
            $permission->description = $input['description'];
            $permission->save();
            return response()->json([
                'permission' => $permission
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $input = Input::get('id');
        if(Input::ajax()) {
            $permission = Permission::destroy($id);
            return response()->json([
                'id' => $id
            ]);
        }
    }
}
